package me.zhengjie.common.utils

import jakarta.persistence.EntityManager
import jakarta.persistence.EntityManagerFactory
import jakarta.persistence.PersistenceUnit
import jakarta.persistence.Query
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Repository
import java.util.logging.Level

@Repository
class EntityManagerHelper {
    @PersistenceUnit
    fun setEntityManager(emf: EntityManagerFactory?) {
        Companion.emf = emf
    }

    companion object {
        // 实体化私有静态实体管理器变量emf
        //private static final EntityManagerFactory emf;
        @Autowired
        private var emf: EntityManagerFactory? = null

        // 实体化私有静态本地线程变量threadLocal
        private var threadLocal: ThreadLocal<EntityManager?>? = null

        // 用来给两个变量赋初值的静态块
        init {
            //emf = Persistence.createEntityManagerFactory("zcxx");
            threadLocal = ThreadLocal()
        }

        val entityManager: EntityManager?
            // 得到实体管理器的方法
            get() {
                var manager = threadLocal!!.get()
                if (manager == null || !manager.isOpen) {
                    manager = emf!!.createEntityManager()
                    threadLocal!!.set(manager)
                }
                return manager
            }

        // 关闭实体管理器的方法
        fun closeEntityManager() {
            val em = threadLocal!!.get()
            threadLocal!!.set(null)
            em?.close()
        }

        // 开始事务的方法
        fun beginTransaction() {
            entityManager!!.transaction.begin()
        }

        // 提交事务的方法
        fun commitTransaction() {
            entityManager!!.transaction.commit()
        }

        // 回滚事务的方法
        fun rollback() {
            entityManager!!.transaction.rollback()
        }

        // 生成查找的方法
        fun createQuery(query: String?): Query {
            return entityManager!!.createQuery(query)
        }

        fun log(string: String?, info: Level?, `object`: Any?) {
            // TODO Auto-generated method stub
        }
    }
}